﻿using QRCoder;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace lwzlz.Common.QR
{
    public class QRCode
    {
        /// <summary>
        /// 普通二维码
        /// </summary>
        /// <param name="strCode"></param>
        /// <returns></returns>
        public static string OrdinaryQR(int id, string strCode, string folder, string fileName)
        {
            var fileUrl = string.Empty;
            using (var ms = new MemoryStream())
            {
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.Q);
                QRCoder.QRCode qrcode = new QRCoder.QRCode(qrCodeData);
                // qrcode.GetGraphic 方法可参考最下发“补充说明”
                Bitmap qrCodeImage = qrcode.GetGraphic(5, Color.Black, Color.White, null, 15, 6, false);
                qrCodeImage.Save(ms, ImageFormat.Jpeg);

                string physicalPath = System.Web.HttpContext.Current.Server.MapPath("~/" + folder);
                if (fileName == "")
                {
                    fileName = ZEncypt.MD5(id.ToString()) + ".png";
                }
                if (!Directory.Exists(physicalPath))
                {
                    Directory.CreateDirectory(physicalPath);
                }
                var filePath = Path.Combine(physicalPath, fileName);
                fileUrl = Path.Combine(folder, fileName);
                ms.Position = 0;
                Bitmap bmpt = new Bitmap(ms);
                bmpt.Save(filePath);
            }
            return fileUrl;
        }
        /// <summary>
        /// 普通二维码
        /// </summary>
        /// <param name="strCode"></param>
        /// <returns></returns>
        public static string OrdinaryQR(string strCode, string folder, string fileName)
        {
            var fileUrl = string.Empty;
            using (var ms = new MemoryStream())
            {
                QRCodeGenerator qrGenerator = new QRCodeGenerator();
                QRCodeData qrCodeData = qrGenerator.CreateQrCode(strCode, QRCodeGenerator.ECCLevel.Q);
                QRCoder.QRCode qrcode = new QRCoder.QRCode(qrCodeData);
                // qrcode.GetGraphic 方法可参考最下发“补充说明”
                Bitmap qrCodeImage = qrcode.GetGraphic(5, Color.Black, Color.White, null, 15, 6, false);
                qrCodeImage.Save(ms, ImageFormat.Jpeg);

                string physicalPath = System.Web.HttpContext.Current.Server.MapPath("~/" + folder);
                if (!Directory.Exists(physicalPath))
                {
                    Directory.CreateDirectory(physicalPath);
                }
                var filePath = Path.Combine(physicalPath, fileName);
                fileUrl = Path.Combine(folder, fileName);
                ms.Position = 0;
                Bitmap bmpt = new Bitmap(ms);
                bmpt.Save(filePath);
            }
            return fileUrl;
        }
    }
}
